<template>
  <BasicDrawer
    class="wyf-drawer"
    v-bind="$attrs"
    @register="registerDrawer"
    :title="getTitle"
    :width="adaptiveWidth"
    :showFooter="showFooter"
    :loading="loading"
    destroyOnClose
  >
    <BasicForm @register="registerForm">
      <template #title1="{ model, field }">
        <span class="wyf-form-item-title">{{ field }}</span>
      </template>
      <template #title2="{ model, field }">
        <span class="wyf-form-item-title">{{ field }}</span>
      </template>
      <template #title3="{ model, field }">
        <span class="wyf-form-item-title">{{ field }}</span>
      </template>
      <template #title4="{ model, field }">
        <span class="wyf-form-item-title">{{ field }}</span>
      </template>
      <!-- v-if="!showFooter" 判断详情 -->
      <template #shjg="{ model, field }">
        <span class="text-red">{{ model[field] }}</span>
        <span class="text-green">{{ model[field] }}</span>
      </template>
    </BasicForm>
    <template #footer="{ confirmLoading }">
      <a-button type="primary" ghost :loading="confirmLoading" @click="handleSubmit">保存修改</a-button>
      <a-button type="primary" :loading="confirmLoading" @click="handleFailedApproved" v-if="type == 'pending'">审核不通过</a-button>
      <a-button type="primary" :loading="confirmLoading" v-if="type == 'pending'" @click="handleSubmit(1)">审核通过</a-button>
      <a-button @click="closeDrawer">取消</a-button>
    </template>
  </BasicDrawer>
  <ApprovedModal @register="registerModal" @success="reload" />
</template>
<script lang="ts" setup>
  import { defineComponent, ref, computed, unref, useAttrs } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../approved.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { reviews, saveOrUpdate, detail } from '../approved.api';
  import { useDrawerAdaptiveWidth } from '/@/hooks/jeecg/useAdaptiveWidth';
  import { useModal } from '/@/components/Modal';
  import ApprovedModal from './ApprovedModal.vue';
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const attrs = useAttrs();
  const isUpdate = ref(true);
  const isFysh = ref(true)
  const rowId = ref('');
  const showFooter = ref(true);
  const type = ref('edit'); //审核 pending
  const loading = ref(false); //审核 pending
  //let isFormDepartUser = false;
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 78,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  // 审核提示注册
  const [registerModal, { openModal }] = useModal();
  //注册drawer
  //表单赋值
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    showFooter.value = data?.showFooter ?? true;
    setDrawerProps({ confirmLoading: true, showFooter: showFooter.value });
    loading.value = true;
    isUpdate.value = !!data?.isUpdate;
    isFysh.value= !!data?.isFysh;
    type.value = data.type || 'edit';

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      const res = await detail({ id: rowId.value });
      //附件赋值
      let fjlx_2_arr = [] as String[],
        fjlx_2_ids_arr = [] as String[],
        fjlx_4_arr = [] as String[],
        fjlx_4_ids_arr = [] as String[],
        fjlx_6_arr = [] as String[],
        fjlx_6_ids_arr = [] as String[],
        fjlx_5_arr = [] as String[],
        fjlx_5_ids_arr = [] as String[];
      const cqrFjids: { fjlx: string; fileurl: string; fjid: string }[] = res.pics || [];
      if (cqrFjids && cqrFjids.length > 0) {
        for (let i = 0; i < cqrFjids.length; i++) {
          if (cqrFjids[i].fjlx == '2') {
            fjlx_2_arr.push(cqrFjids[i].fileurl);
            fjlx_2_ids_arr.push(cqrFjids[i].fjid);
          } else if (cqrFjids[i].fjlx == '4') {
            fjlx_4_arr.push(cqrFjids[i].fileurl);
            fjlx_4_ids_arr.push(cqrFjids[i].fjid);
          } else if (cqrFjids[i].fjlx == '5') {
            fjlx_5_arr.push(cqrFjids[i].fileurl);
            fjlx_5_ids_arr.push(cqrFjids[i].fjid);
          } else if (cqrFjids[i].fjlx == '6') {
            fjlx_6_arr.push(cqrFjids[i].fileurl);
            fjlx_6_ids_arr.push(cqrFjids[i].fjid);
          }
        }
      }
      const fjlx_2 = fjlx_2_arr.join(',');
      const fjlx_2_ids = fjlx_2_ids_arr.join(',');
      const fjlx_4 = fjlx_4_arr.join(',');
      const fjlx_4_ids = fjlx_4_ids_arr.join(',');
      const fjlx_5 = fjlx_5_arr.join(',');
      const fjlx_5_ids = fjlx_5_ids_arr.join(',');
      const fjlx_6 = fjlx_6_arr.join(',');
      const fjlx_6_ids = fjlx_6_ids_arr.join(',');

      data.record.jyrlx = res.hoperator.jyrlx;
      data.record.jyrzjhm = res.hoperator.jyrzjhm;
      data.record.jyrlxdh = res.hoperator.jyrlxdh;
      data.record.jyrxm = res.hoperator.jyrxm;
      data.record.jyrdwmc = res.hoperator.jyrdwmc;
      data.record.tyshxydm = res.hoperator.tyshxydm;

      data.record.cqrlx = res.hpownerList && res.hpownerList[0]?.cqrlx;
      data.record.cqrdwmc = res.hpownerList && res.hpownerList[0]?.cqrdwmc;
      data.record.cqrxm = res.hpownerList && res.hpownerList[0]?.cqrxm;
      data.record.cqrlxdh = res.hpownerList && res.hpownerList[0]?.cqrlxdh;
      data.record.cqrtyshxydm = res.hpownerList && res.hpownerList[0]?.tyshxydm;
      data.record.cqrzjhm = res.hpownerList && res.hpownerList[0]?.cqrzjhm;

      let xzqh; //      '330482101008'
      if (res.xzqh && res.xzqh.length == 4) {
        xzqh = [res.xzqh];
      } else if (res.xzqh && res.xzqh.length == 6) {
        xzqh = [res.xzqh.substring(0, 4), res.xzqh];
      } else if (res.xzqh && res.xzqh.length == 9) {
        xzqh = [res.xzqh.substring(0, 4), res.xzqh.substring(0, 6), res.xzqh];
      } else if (res.xzqh && res.xzqh.length == 12) {
        xzqh = [res.xzqh.substring(0, 4), res.xzqh.substring(0, 6), res.xzqh.substring(0, 9), res.xzqh];
      }
      const fitlerxzqh = xzqh.join(',');
      data.record = { ...data.record, ...res, fjlx_2, fjlx_2_ids, fjlx_4, fjlx_5, fjlx_4_ids, fjlx_6, fjlx_6_ids, fjlx_5_ids, xzqh: fitlerxzqh };
    }
    // 无论新增还是编辑，都可以设置表单值
    if (typeof data.record === 'object') {
      setFieldsValue({
        ...data.record,
      });
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !showFooter.value });
    setDrawerProps({ confirmLoading: false });
    loading.value = false;
  });
  //获取标题
  const getTitle = computed(() => {
    if(unref(isFysh)) {
        return '房源审核';
    }
    if (!unref(isUpdate)) {
      return '新增房源';
    } else {
      return unref(showFooter) ? '编辑房源' : '房源详情';
    }
  });
  const { adaptiveWidth } = useDrawerAdaptiveWidth();

  //提交事件
  async function handleSubmit(flag) {
    try {
      let values = await validate();
      console.log('提交数据', values);
      setDrawerProps({ confirmLoading: true });
      // values.userIdentity === 1 && (values.departIds = '');
      let isUpdateVal = unref(isUpdate);
      // -update-begin--author:liaozhiyang---date:20240702---for：【TV360X-1737】部门用户编辑接口，增加参数updateFromPage:"deptUsers"
      //#TODO 请求分编辑和审核
      let params;
      if (flag == 1) {
        params = {
          houseId: rowId.value,
          shbz: 1,
          // shyj: '',
        };
        await reviews(params);
      } else {
        let xzqy = values.xzqh.split(',');
        params = { ...values, xzqh: xzqy[xzqy.length - 1] };
        params.fjlx_2_ids = params.fjlx_2_ids && !Array.isArray(params.fjlx_2_ids) ? params.fjlx_2_ids.split(',') : [];
        params.fjlx_4_ids = params.fjlx_4_ids && !Array.isArray(params.fjlx_4_ids) ? params.fjlx_4_ids.split(',') : [];
        params.fjlx_5_ids = params.fjlx_5_ids && !Array.isArray(params.fjlx_5_ids) ? params.fjlx_5_ids.split(',') : [];
        params.fjlx_6_ids = params.fjlx_6_ids && !Array.isArray(params.fjlx_6_ids) ? params.fjlx_6_ids.split(',') : [];
        params.fjids = [...params.fjlx_2_ids, ...params.fjlx_4_ids, ...params.fjlx_5_ids, ...params.fjlx_6_ids];
        // delete params.fjlx_2_ids;
        // delete params.fjlx_4_ids;
        // delete params.fjlx_6_ids;
        // delete params.fjlx_5_ids;
        params.cqrList = [
          {
            cqrlx: params.cqrlx,
            cqrdwmc: params.cqrdwmc,
            cqrTyshxydm: params.cqrtyshxydm,
            cqrxm: params.cqrxm,
            cqrlxdh: params.cqrlxdh,
            cqrzjhm: params.cqrzjhm,
          },
        ];
        await saveOrUpdate(params, isUpdateVal);
      }
      //关闭弹窗
      closeDrawer();
      //刷新列表
      emit('success', { isUpdateVal, values });
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
  /**
   * 审核弹窗
   */
  function handleFailedApproved() {
    openModal(true, {
      record: {
        houseId: rowId.value,
      },
      isUpdate: true,
    });
  }

  function reload() {
    closeDrawer();
    //刷新列表
    emit('success');
  }
</script>
